<template>
  <div class="announcement-container">
    <div class="page-header">
      <h2>公告管理</h2>
    </div>
    
    <el-card class="main-card">
      <!-- 操作栏 -->
      <div class="operation-bar">
        <div class="search-box">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入公告标题搜索"
            prefix-icon="el-icon-search"
            clearable
            @clear="handleSearch"
            @keyup.enter.native="handleSearch"
          >
          </el-input>
          <el-button type="primary" @click="handleSearch" icon="el-icon-search">搜索</el-button>
        </div>
        <el-button type="success" icon="el-icon-plus" @click="showAddDialog">新增公告</el-button>
      </div>

      <!-- 公告列表 -->
      <el-table
        :data="announcements"
        style="width: 100%"
        border
        stripe
      >
        <el-table-column prop="title" label="公告标题" min-width="200"></el-table-column>
        <el-table-column prop="publisher" label="发布人" width="120"></el-table-column>
        <el-table-column prop="publishedAt" label="发布时间" width="180">
          <template slot-scope="scope">
            {{ formatDate(scope.row.publishedAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="showDetailDialog(scope.row)"
            >详情</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑公告对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增公告' : '编辑公告'"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <el-form :model="announcementForm" :rules="formRules" ref="announcementForm" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="announcementForm.title"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            type="textarea"
            :rows="6"
            v-model="announcementForm.content"
            placeholder="请输入公告内容"
          ></el-input>
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            class="upload-demo"
            action="/upload"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 公告详情对话框 -->
    <el-dialog
      title="公告详情"
      :visible.sync="detailDialogVisible"
      width="50%"
    >
      <div class="announcement-detail">
        <h3>{{ currentAnnouncement.title }}</h3>
        <div class="meta-info">
          <span>发布人：{{ currentAnnouncement.publisher }}</span>
          <span>发布时间：{{ formatDate(currentAnnouncement.publishedAt) }}</span>
        </div>
        <div class="content" v-html="currentAnnouncement.content"></div>
        <div class="image" v-if="currentAnnouncement.image">
          <img :src="currentAnnouncement.image" alt="公告图片">
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Announcement',
  data() {
    return {
      // 搜索关键词
      searchKeyword: '',
      
      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,
      
      // 公告列表
      announcements: [
        
      ],
      
      // 对话框控制
      dialogVisible: false,
      detailDialogVisible: false,
      dialogType: 'add', // 'add' 或 'edit'
      
      // 表单数据
      announcementForm: {
        title: '',
        content: '',
        image: ''
      },
      
      // 当前查看的公告
      currentAnnouncement: {},
      
      // 表单验证规则
      formRules: {
        title: [
          { required: true, message: '请输入公告标题', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入公告内容', trigger: 'blur' }
        ]
      }
    }
  },
  
  methods: {
    // 格式化日期
    formatDate(date) {
      if (!date) return ''
      return date.replace('T', ' ').substring(0, 16)
    },
    
    // 搜索
    handleSearch() {
      // TODO: 实现搜索功能
      console.log('搜索关键词：', this.searchKeyword)
    },
    
    // 分页
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchAnnouncements()
    },
    
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchAnnouncements()
    },
    
    // 显示新增对话框
    showAddDialog() {
      this.dialogType = 'add'
      this.announcementForm = {
        title: '',
        content: '',
        image: ''
      }
      this.dialogVisible = true
    },
    
    // 显示详情对话框
    showDetailDialog(row) {
      this.currentAnnouncement = { ...row }
      this.detailDialogVisible = true
    },
    
    // 删除公告
    handleDelete(row) {
      this.$confirm('确认删除该公告?', '提示', {
        type: 'warning'
      }).then(() => {
        // TODO: 调用删除接口
        this.$message.success('删除成功')
      })
    },
    
    // 提交表单
    handleSubmit() {
      this.$refs.announcementForm.validate(async valid => {
        if (valid) {
          // const form = new FormData()
          // form.append('title', this.announcementForm.title)
          // form.append('content', this.announcementForm.content)
          // // form.append('image', this.announcementForm.image)
          // form.append('publisher', '当前登录用户') // TODO: 获取当前登录用户
          //
          try {
            const res = await this.$http.post('/platform/announcement/addAnnouncement', {
              title: this.announcementForm.title,
              content: this.announcementForm.content,
              image: this.announcementForm.image,
              publisher: '当前登录用户' // TODO: 获取当前登录用户
            })
            if (res.data.code === 200) {
              this.$message.success('发布成功')
              this.dialogVisible = false
              this.fetchAnnouncements()
            } else {
              this.$message.error(res.data.message || '发布失败')
            }
          } catch (error) {
            this.$message.error('发布失败')
          }
        }
      })
    },
    
    // 上传相关
    handleUploadSuccess(res, file) {
      this.announcementForm.image = res.url
    },
    
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('只能上传图片文件!')
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
      }
      return isImage && isLt2M
    },
    
    // 获取公告列表
    fetchAnnouncements() {
      // TODO: 实现获取公告列表接口
      this.$http.get('/platform/announcement/selectAnnouncement').then(res => {
        if (res.data.code === 200) {
          console.log('公告列表：', res.data.data)
          this.announcements = res.data.data.reverse() // 对数据进行倒序处理
          this.total = 10
        }
      })
    }
  },
  
  created() {
    this.fetchAnnouncements()
  }
}
</script>

<style scoped>
.announcement-container {
  padding: 20px;
  background: #f0f2f5;
  min-height: calc(100vh - 40px);
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  color: #303133;
  margin: 0;
  font-size: 24px;
  font-weight: 500;
}

.main-card {
  background: #fff;
  border-radius: 4px;
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-box {
  display: flex;
  gap: 10px;
}

.search-box .el-input {
  width: 300px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.announcement-detail {
  padding: 20px;
}

.announcement-detail h3 {
  margin: 0 0 20px 0;
  text-align: center;
  font-size: 20px;
}

.meta-info {
  color: #909399;
  font-size: 14px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.content {
  line-height: 1.6;
  white-space: pre-wrap;
}

.image {
  margin-top: 20px;
  text-align: center;
}

.image img {
  max-width: 100%;
  max-height: 400px;
}
</style> 